using FluentNHibernate.Cfg;
using FluentNHibernate.Framework;
using Microsoft.Practices.ServiceLocation;
using NCommon.Data;
using NCommon.Data.NHibernate;
using Roommate.Infrastructure.Persistence;
using StructureMap;

namespace Roommate.Infrastructure.IoC
{
    public class Bootstrapper
    {
        private static bool hasStarted;
        public virtual void BootstrapStructureMap()
        {
            //ObjectFactory.Initialize(x => { x.AddRegistry(new WebRegistry()); x.AddRegistry(new ControllerConfig()); });
            var cfg = new SQLiteConfiguration()
                .UsingFile("c:\\temp\\roommate.db")
               .Raw("proxyfactory.factory_class",
                     "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");


            var sessionSource = new SessionSource(cfg.ToProperties(), new RoommatePersistenceModel());

           NHUnitOfWorkFactory.SetSessionProvider(sessionSource.CreateSession);


            ObjectFactory.Configure(x =>
            {
                x.Scan(y =>
                {
                    y.Assembly("Roommate.Services");
                    y.WithDefaultConventions();
                });

                x.ForRequestedType<IUnitOfWorkFactory>().TheDefaultIsConcreteType<NHUnitOfWorkFactory>().AsSingletons();

            });

            ObjectFactory.AssertConfigurationIsValid();
        }
        public static void Restart()
        {
            if (hasStarted)
            {
                ObjectFactory.ResetDefaults();
            }
            else
            {
                Bootstrap(); 
                hasStarted = true;
            }

            ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator());
        }

        protected static void Bootstrap()
        {
            new Bootstrapper().BootstrapStructureMap();
        }
    }

}